<template>
	<view class="android-container">
		<!-- 群主信息 -->
		<scroll-view class="form-scroll" scroll-y>
			<view class="form-card">
				<view class="form-title"><text>👤 邻里管家信息更新</text></view>

				<!-- 头像上传 -->
				<view class="owninfo">
					<view class="avatar-upload">
						<image :src="user.nicPic" mode="aspectFit" class="avatar-image" />
					</view>

					<!-- 基本信息 -->
					<view class="nameinfo">
						<view class="form-name">
							<input class="" type="text" disabled="true" v-model="own.name" @blur="handleblus" placeholder="邻里管家姓名" />
						</view>
						<view class="form-name">
							<input class="" disabled="true" v-model="own.cardId" type="number" @blur="handleblus" placeholder="身份证号码"  />
						</view>
						<view class="form-name">
							<text class="editlabel">服务手机号</text>
							<input class="" v-model="own.telphone" type="tel" @blur="handleblus" placeholder="服务手机号" />
						</view>
					</view>
				</view>
				<text class="editlabel">营业场地详细地址</text>
				<input class="form-input full-width" type="text" @blur="handleblus" v-model="own.address" placeholder="营业场地详细地址" />
			     <text class="editlabel">服务宗旨</text>
				<textarea class="form-textarea" v-model="own.signature" @blur="handleblus" placeholder="服务承诺和宗旨...12个字以内" maxlength="18" />
			</view>

			<!-- 群信息 -->
			<view class="form-card">
				<view class="form-title">
					<text>👥 邻里服务信息更新</text>
				</view>
                 <text class="editlabel">邻里群名称</text>
				<input class="form-input full-width" type="text" @blur="handleblus" v-model="groupInfo.groupName" placeholder="邻里名称" />

				<view class="form-row">
					<view class="upload-wrap" @click="uploadGroupImage">
						<image v-if="groupInfo.groupPicPath" :src="groupInfo.groupPicPath" mode="aspectFit" class="group-image" />
						<text v-else class="upload-text">上传邻里标志</text>
					</view>
				</view>
                <text class="editlabel">邻里介绍</text>
				<textarea class="form-textarea" v-model="groupInfo.signature" placeholder="邻里简介，20个字以内" />
			</view>
		</scroll-view>

		<!-- 底部按钮 -->
		<view class="fixed-footer">
			<button class="submit-btn" @click="formSubmit">确认更改</button>
		</view>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();
const app=getApp().globalData
export default {
	data() {
		return {
			agree: false,
			user: {},
			submitting: false,
			photo: '',
			groupPicPath: '',
			own: {
				ownId: '',
				name: '',
				signature: '',
				cardId: '',
				address: '',
				telphone: '',
				ownLocation: null
			},
	         newphoto:false,
			groupInfo: {
				groupName: '',
				location: { longitude: 0, latitude: 0 },
				polygons: null,
				groupPicPath: '',
				signature: '',
				aMapLocation: null
			}
		};
	},

	mounted() {
		uni.onKeyboardHeightChange((res) => {
			this.buttonBottom = res.height ? res.height + 20 : 20;
		});
	},
	onLoad() {
		this.user = app.user;
		this.own.userId = this.user.userId;
		this.getGroup();
	},

	methods: {
		async getGroup() {
			try {
				const res =await db
					.collection('Group')
					.where({
						ownId: this.user.userId
					})
					.get();
					console.log('kdfjasldfj',res)
					
				if (res.data === 0) {
					uni.showModal({
						title: '权限不足',
						content: '只有申请者有权限更改！！'
					});
					return;
				}
				this.groupInfo = res.data[0];
				this.own = res.data[0].own;
			} catch (e) {
				console.error(e);
			}
		},

		handleblus() {
			// 在输入框获取焦点时，明确设置输入类型
			uni.hideKeyboard();
		},

		// 上传群图片
		uploadGroupImage() {
		
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'], // 压缩图
				sourceType: ['album'], // 从相册选择
				success: (res) => {
					this.groupInfo.groupPicPath = res.tempFilePaths[0];
					this.newphoto=ture
				}
			});
		},

		// 表单提交
		async formSubmit() {
			if (this.submitting) return;

			this.submitting = true;
			if (!this.validateForm()) return;

			try {
				var submitData={}
				if(this.newphoto){	const [groupPicRes] = await Promise.all([
					this.uploadFile({
						filePath: this.groupInfo.groupPicPath,
						type: 'groupPic'
					})
				]);

				// 构造提交数据
				 submitData = {
					own: {
						ownId: this.user.userId,
						...this.own
					},
					...this.groupInfo,
					groupPicPath: groupPicRes
				};
				}else{
				submitData = {
					own: {
							ownId: this.user.userId,
							...this.own
						},
						...this.groupInfo,
						
					};
					
				}
			

				// 提交到数据库
			const id=await db.collection('Group').where({ ownId: this.user.userId }).update(submitData);
			 if(id.code===0&&id.updated>0){
				 uni.showToast({
				 	title:'更新成功'
				 })
				 	setTimeout(() => uni.navigateBack(), 1500);
				 
			 }
			
			
			} catch (error) {
				console.error('修改失败:', error);
				uni.showToast({
					title: `修改失败: ${error.errMsg || error.message}`,
					icon: 'none',
					duration: 3000
				});
			} finally {
				this.submitting = false;
			}
		},

		// 封装的上传方法
		async uploadFile({ filePath, type }) {
			uni.showLoading({
				title: "图片上传中...",
				mask: true
			});
			if (!filePath) throw new Error('请先上传文件');

			try {
				// 上传原始文件
				const uploadRes = await uniCloud.uploadFile({
					cloudPath: `${type}/${Date.now()}_${Math.random().toString(36).slice(2)}.jpg`,
					filePath
				});

				// 获取临时访问地址
				const { fileList } = await uniCloud.getTempFileURL({
					fileList: [uploadRes.fileID]
				});

				return fileList[0].tempFileURL;
			} catch (error) {
				console.error(`图片上传失败:`, error);
			} finally {
				uni.hideLoading();
			}
		},

		// 表单验证
		validateForm() {
			const validations = [
				{ condition: !!this.own.telphone, message: '请填写服务电话' },
				{
					condition: /^1[3-9]\d{9}$/.test(this.own.telphone),
					message: '手机号格式错误'
				}
			];

			for (const item of validations) {
				if (!item.condition) {
					uni.showToast({
						title: item.message,
						icon: 'none',
						duration: 2000
					});
					return false;
				}
			}
			return true;
		}
	}
};
</script>

<style lang="scss" scoped>
/* 整体容器样式 */
.android-container {
	padding: 20px;
	background-color: #f4f4f4;
	min-height: 100vh;
	box-sizing: border-box;
}

/* 滚动区域样式 */
.form-scroll {
	height: calc(100vh - 80px);
	margin-bottom: 200rpx;
	overflow-y: auto;
}

/* 卡片样式 */
.form-card {
	background-color: #ffffff;
	border-radius: 10px;
	padding: 20px;
	margin-bottom: 20px;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
}

/* 标题样式 */
.form-title {
	font-size: 20px;
	font-weight: 600;
	color: #333333;
	margin-bottom: 20px;
	padding-left: 10px;
	border-left: 5px solid #007aff;
}
.editlabel{
	font-size: 28rpx;
	color: #007aff;
}

/* 群主信息部分 */
.owninfo {
	display: flex;
	align-items: center;
	margin-bottom: 20px;
}

/* 头像上传区域样式 */
.avatar-upload {
	width: 120px;
	height: 120px;
	border-radius: 60px;
	background-color: #e0e0e0;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	margin-right: 20px;
}

.avatar-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
	border-radius: 60px;
}
.formlable {
	display: flex;
	flex-direction: row;
	justify-content: center;
	width: 250rpx;
	height: 80rpx;
	color: #ffffff;
	border-radius: 15rpx;
	background-color: #007aff;
	align-items: center;
	margin-right: 20rpx;
}
.radius {
	width: 280rpx;
	background-color: #ebebeb;
	color: #007aff;
}
.upload-hint {
	display: flex;
	flex-direction: column;
	text-align: center;
	color: #666666;
	font-size: 14px;
}

/* 基本信息区域样式 */
.nameinfo {
	flex: 1;
}

.form-name {
	margin-bottom: 10px;
}

// 修复身份证号码、业务手机号输入框样式
.form-name input {
	width: 100%;
	height: 40px;
	border: 1px solid #ccc;
	border-radius: 5px;
	padding: 0 10px;
	font-size: 14px;
	background-color: #fff; // 添加白色背景，使其更明显
}

/* 全宽输入框样式 */
.form-input.full-width {
	width: 100%;
	height: 40px;
	border: 1px solid #ccc;
	border-radius: 5px;
	padding: 0 10px;
	font-size: 14px;
	margin-bottom: 15px;
}

/* 文本域样式 */
.form-textarea {
	width: 100%;
	border: 1px solid #ccc;
	border-radius: 5px;
	padding: 10px;
	font-size: 14px;
	height: 40px;
	resize: vertical;
	margin-bottom: 15px;
}

/* 群信息部分 */
// 修复群信息部分输入框样式
.location-row input,
.form-input.full-width {
	height: 40px;
	border: 1px solid #ccc;
	border-radius: 5px;
	padding: 0 10px;
	font-size: 14px;
	background-color: #fff; // 添加白色背景，使其更明显
}

.location-row {
	display: flex;
	align-items: center;
	margin-bottom: 15px;
}

.location-row input {
	flex: 1;
	margin-right: 10px;
}

/* 上传群标志区域样式 */
.upload-wrap {
	width: 120px;
	height: 120px;
	border-radius: 10px;
	background-color: #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0 auto 15px;
}

.group-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
	border-radius: 10px;
}

.upload-text {
	color: #666666;
	font-size: 14px;
	text-align: center;
}

/* 底部按钮样式 */
.fixed-footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #ffffff;
	padding: 15px 20px;
	box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
	text-align: center;
}

.submit-btn {
	width: 100%;
	height: 48px;
	line-height: 48px;
	background-color: #007aff;
	color: #ffffff;
	font-size: 16px;
	border: none;
	border-radius: 24px;
	transition: all 0.2s ease;
	cursor: pointer;
}

.submit-btn:active {
	opacity: 0.9;
	transform: scale(0.98);
}
</style>
